import React, { Component } from 'react'
import axios from 'axios'
import './lifecycle.css'
export default class LifeCycle extends Component {
  /*
    constructor的作用有两个
    1）初始化state数据的
    2）用来改变this指向的
    如果不需要在contructor中完成这两项，就可以不去使用constructor
  */
  constructor(props){
    super(props)
    console.log('--------constructor--------');
    this.state={
        count:0,
        movies:[]
    }
    //在构造函数中通过如下方式进行this执行的改变this.方法名=this.方法名.bind(this)
    this.increment=this.increment.bind(this)
  }
  async getAllMovies(){
    const {data:{movies}}=await axios.get('https://www.fastmock.site/mock/4441a79ad5f884f83b784cf4c588bdb6/movies/getHotMovies')
    this.setState(()=>{
      return{
        movies
      }
    })
  }
  componentDidMount(){
    console.log('--------componentDidMount------------');
    this.getAllMovies()
  }
  increment(){
    this.setState(()=>{
        return{
            count:this.state.count+1
        }
    })
  }
  render() {
    console.log('----------render------------');
    return (
      <div>
        <h1>生命周期演示</h1>
        <div>{this.state.count}</div>
        <button onClick={this.increment}>+1</button>
        <hr />
        <div className='box'>
            {
              this.state.movies.map((item,index)=><div className='item'>
                  <div className='item-top'>
                    <img src={item.imgSrc} alt="" />
                  </div>
                  <div className='item-bottom'></div>
              </div>)
            }
        </div>
      </div>
    )
  }
}
